import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getStorage, setStorage } from '@/utils/storage'
import { resetRouter } from '@/router'
import { getWebInfo } from '@/api/public'

import { encryptByAES } from '@/utils/user'

import '@/utils/storage'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    userInfo: getStorage("userInfo", true),
    webInfo: getStorage("webInfo", true)
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_WEB_INFO: (state, webInfo) => {
    state.webInfo = webInfo
  },
}

const actions = {
  // 用户登录
  async login({ commit }, userInfo) {
    let {
      username,
      password,
      validateCode,
      uuid,
      salt,
    } = userInfo

    password = encryptByAES(password, salt, salt)
    const data = {
      username,
      password,
      code: validateCode,
      uuid,
      salt,
      from: 'web'
    }
    const params = {
      code: validateCode,
      uuid
    }


    const resData = await login(params, data);
    if (resData) {
      commit('SET_TOKEN', resData.token)
      commit('SET_USER_INFO', resData)
      setToken(resData.token)
      setStorage("userInfo", resData)
      return true
    } else {
      throw "login error"
    }
  },

  // 退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first 
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  // 设置webInfo
  setWebInfo({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      getWebInfo().then(res => {
        commit('SET_WEB_INFO', res)
        dispatch('settings/changeSetting', { key: 'title', value: res.websiteName }, { root: true })
        setStorage("webInfo", res)
        !document.title && (document.title = res.websiteName)
        resolve(res.websiteName)
      }).catch(error => {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

